<template>
  <button @click="addItem">添加</button>
  <div class="drag-content" ref="contentRef">
    <template v-for="item in list" :key="item.id">
      {{ item.width }}
      <vue-draggable-resizable
        v-model:w="item.style.width"
        v-model:h="item.style.height"
        v-model:x="item.style.left"
        v-model:y="item.style.top"
        :min-width="10"
        :min-height="10"
        :parent="true"
        :debug="false"
        :snap="true"
        :snapTolerance="1"
        @refLineParams="getRefLineParams"
      >
        <div v-bind="item">{{ item.content }}</div>
      </vue-draggable-resizable>
    </template>

    <!--辅助线-->
    <span
      class="ref-line v-line"
      v-for="item in vLine"
      :key="item.id"
      v-show="item.display"
      :style="{
        left: item.position,
        top: item.origin,
        height: item.lineLength,
      }"
    />
    <span
      class="ref-line h-line"
      v-for="item in hLine"
      :key="item.id"
      v-show="item.display"
      :style="{ top: item.position, left: item.origin, width: item.lineLength }"
    />
    <!--辅助线END-->
  </div>
</template>

<script>
import VueDraggableResizable from "./components/vue-draggable-resizable";
import { defineComponent, reactive, ref, toRefs } from "vue";
export default defineComponent({
  name: "content",
  components: {
    VueDraggableResizable,
  },
  setup() {
    const state = reactive({
      vLine: [],
      hLine: [],
      list: [],
    });
    const contentRef = ref(null);

    // 辅助线回调事件
    const getRefLineParams = (params) => {
      const { vLine, hLine } = params;
      let id = 0;
      state.vLine = vLine.map((item) => {
        item["id"] = ++id;
        return item;
      });
      state.hLine = hLine.map((item) => {
        item["id"] = ++id;
        return item;
      });
    };

    const addItem = () => {
      state.list.push({
        id: +new Date(),
        content: "内容",
        style: {
          width: 100,
          height: 20,
          background: `rgb(
            ${parseInt(Math.random() * 255)},
            ${parseInt(Math.random() * 255)},
            ${parseInt(Math.random() * 255)}
            )`,
        },
      });
    };

    return {
      getRefLineParams,
      ...toRefs(state),
      contentRef,
      addItem,
    };
  },
});
</script>

<style scoped>
@import url("./components/vue-draggable-resizable.css");
.drag-content {
  position: relative;
  width: 1200px;
  height: 500px;
  margin: 0 auto;
  background-color: #eee;
}
</style>
